﻿using UnityEngine;
using System.Text.RegularExpressions;
using System;

namespace SangsTools
{
    public static class MyJsonTools
    {
        /// <summary>
        /// 把 LitJson 的字符串转成 UTF-8 格式
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string ToUTF8(this string json)
        {
            //正则表达式 表示的字符串转换成 非正则表达式 的字符串
            //如果有字符串形式的json数据，装换后会异常
            //string strJson = Regex.Unescape(json.ToJson());

            //用正则查找被替换编码的字符，再转换回来
            Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
            string strJson = reg.Replace(json, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
            return strJson;
        }

        public static string ToJson(this object jsonObject)
        {
            return jsonObject != null ? JsonUtility.ToJson(jsonObject) : null;
        }

        public static T FromJson<T>(this object jsonObject, string json)
        {
            return JsonUtility.FromJson<T>(json);
        }

        public static bool TryFromJson<T>(this object jsonObject, string json, out T obj)
        {
            try
            {
                obj = JsonUtility.FromJson<T>(json);
                return true;
            }
            catch
            {
                obj = default(T);
                return false;
            }
        }

#if UNITY_EDITOR
        public static bool SaveJsonFile(string json, string savePath = null, string fileName = null,bool showWindow=false)
        {
            if (string.IsNullOrEmpty(savePath) || string.IsNullOrEmpty(fileName))
                showWindow= true;

            string path = string.Empty;
            if (showWindow)
                path = UnityEditor.EditorUtility.SaveFilePanel("保存 Json 文件", string.IsNullOrEmpty(savePath) ? Application.dataPath : savePath,
                    string.IsNullOrEmpty(fileName) ? "JsonData" : fileName, "json");
            else
                path = $"{Application.dataPath}/{savePath}/{fileName}.json";

            Debug.Log($"Path : {path}\nJson : {json}");

            if (path.Length != 0)
            {
                byte[] data = System.Text.UnicodeEncoding.UTF8.GetBytes(json);
                System.IO.File.WriteAllBytes(path, data);
                return true;
            }
            else
            {
                Debug.Log("放弃保存");
                return false;
            }
        }
#endif
    }
}